<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="查评要素" prop="evaluationElements">
        <el-input
          v-model="queryParams.evaluationElements"
          placeholder="请输入查评要素"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="查评对象" prop="evaluateObject">
        <el-input
          v-model="queryParams.evaluateObject"
          placeholder="请输入查评对象"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否存在问题" prop="isProblem" label-width="100px">
        <el-select
          v-model="queryParams.isProblem"
          class="full-width-input"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option label="是" value="1"></el-option>
          <el-option label="否" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="检查人" prop="examiner">
        <el-input
          v-model="queryParams.examiner"
          placeholder="请输入检查人"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="20" class="contnet">
      <el-col
        :span="4"
        :xs="24"
        style="border-right: 1px solid rgb(238, 238, 238)"
        id="left-tree"
        class="left-tree"
      >
        <div class="head-container">
          <el-input
            v-model="filterText"
            placeholder="请输入事件名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            style="height:430px;overflow-y: scroll"
            class="filter-tree"
            :data="treeData"
            ref="tree"
            node-key="id"
            :filter-node-method="filterNode"
            :props="defaultProps"
            @node-click="handelTreeChange"
          ></el-tree>
          <div
            id="resize"
            class="resize"
            title="收缩侧边栏"
            @mousemove="dragControllerDiv"
          >
            ⋮
          </div>
        </div>
      </el-col>
      <el-col
        id="right-content"
        class="right-content"
        :span="20"
        :xs="24"
        style="border-right: 1px solid rgb(238, 238, 238); float: right"
      >
        <el-table
          v-loading="loading"
          :data="evaluationList"
          @selection-change="handleSelectionChange"
          @row-dblclick="handleRowDblClick"
          border
        >
          <el-table-column
            type="selection"
            width="55"
            align="center"
            header-align="left"
          />
          <el-table-column label="序号" type="index" width="50" align="left" />
          <!--          <el-table-column-->
          <!--            label="查评事件"-->
          <!--            align="center"-->
          <!--            prop="reviewEvents"-->
          <!--          />-->
          <el-table-column
            label="查评要素"
            align="left"
            prop="evaluationElements"
            min-width="250"
            :show-overflow-tooltip="true"
            class="el-tooltip__popper"
          >
            <template slot-scope="scope">
              <a
                @click.prevent="handleLinkClick(scope.row)"
                style="color: #409eff"
              >
                {{ scope.row.evaluationElements }}
              </a>
            </template>
          </el-table-column>
          <el-table-column
            label="查评对象"
            align="left"
            prop="evaluateObject"
            min-width="170"
          />
          <el-table-column
            label="是否存在问题"
            align="left"
            prop="isProblem"
            min-width="100"
          >
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.isProblem === '0' ? 'success' : 'danger'"
                >{{ getTagText(scope.row.isProblem) }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="检查人" align="center" prop="examiner" />
          <el-table-column
            label="创建时间"
            align="left"
            prop="createTime"
            min-width="150"
          />
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  addGroping,
  updateGroping,
  listGropingRecordTree,
  listGropingRecord,
} from "@/api/system/review/groping";
import { ElTable, ElTableColumn } from "element-ui";
export default {
  name: "Evaluation",
  directives: {
    drag: {
      inserted: function (el) {
        console.log("===", el);
        const dragDom = el;
        dragDom.style.cursor = "e-resize";
        dragDom.onmousedown = (e) => {
          // 鼠标按下，计算当前元素距离可视区的距离
          const disX = e.clientX;
          const w = dragDom.clientWidth;
          const minW = 240;
          const maxW = 600;
          var nw;
          document.onmousemove = function (e) {
            // 通过事件委托，计算移动的距离
            const l = e.clientX - disX;
            // 改变当前元素宽度，不可超过最小最大值
            nw = w + l;
            nw = nw < minW ? minW : nw;
            nw = nw > maxW ? maxW : nw;
            dragDom.style.width = `${nw}px`;
          };

          document.onmouseup = function (e) {
            document.onmousemove = null;
            document.onmouseup = null;
          };
        };
      },
    },
  },
  data() {
    return {
      treeData: [],
      defaultProps: {
        children: "children", // 修改 children 属性名称
        label: "year", // 修改 label 属性名称
      },
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 项目查评表格数据
      evaluationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reviewEvents: undefined,
        evaluationElements: undefined,
        examinerCode: undefined,
        examiner: undefined,
        isApply: undefined,
        lookWorkCase: undefined,
        evaluateCase: undefined,
        isInnovate: undefined,
        evaluateObject: undefined,
        backingMaterial: undefined,
        lookPapersCase: undefined,
        deduct: undefined,
        isProblem: undefined,
        problem: undefined,
        isGreatProblem: undefined,
        rectifySuggest: undefined,
        scenePhoto: undefined,
        reviewStatus: undefined,
        reviewStandard: undefined,
        scoreStandard: undefined,
        isDelete: undefined,
        evaGroupId: undefined,
        deptCode: undefined,
        deptName: undefined,
        responsibleCode: undefined,
        responsibleName: undefined,
        requireOkTime: undefined,
        okTime: undefined,
        requireSituation: undefined,
        okPhoto: undefined,
        deductPursuant: undefined,
        createBy: undefined,
        refId: undefined,
        reviewEventsId: undefined,
      },
      // 表单参数
      form: {},
      dateRange: [],
      //事件名称
      filterText: "",
      // 表单校验
      rules: {
        id: [{ required: true, message: "主键id不能为空", trigger: "blur" }],
        reviewEvents: [
          { required: true, message: "查评事件不能为空", trigger: "blur" },
        ],
        evaluationElements: [
          { required: true, message: "查评要素不能为空", trigger: "blur" },
        ],
        examinerCode: [
          { required: true, message: "检查人编号不能为空", trigger: "blur" },
        ],
        examiner: [
          { required: true, message: "检查人不能为空", trigger: "blur" },
        ],
        isApply: [
          { required: true, message: "是否适用不能为空", trigger: "blur" },
        ],
        lookWorkCase: [
          { required: true, message: "查看工作情况不能为空", trigger: "blur" },
        ],
        evaluateCase: [
          { required: true, message: "查评情况不能为空", trigger: "blur" },
        ],
        isInnovate: [
          { required: true, message: "是否创新不能为空", trigger: "blur" },
        ],
        evaluateObject: [
          { required: true, message: "查评对象不能为空", trigger: "blur" },
        ],
        backingMaterial: [
          { required: true, message: "支撑材料不能为空", trigger: "blur" },
        ],
        lookPapersCase: [
          { required: true, message: "查证情况不能为空", trigger: "blur" },
        ],
        deduct: [{ required: true, message: "扣分不能为空", trigger: "blur" }],
        isProblem: [
          { required: true, message: "是否存在问题不能为空", trigger: "blur" },
        ],
        problem: [
          { required: true, message: "存在问题不能为空", trigger: "blur" },
        ],
        isGreatProblem: [
          { required: true, message: "是否重大问题不能为空", trigger: "blur" },
        ],
        rectifySuggest: [
          { required: true, message: "整改建议不能为空", trigger: "blur" },
        ],
        scenePhoto: [
          { required: true, message: "现场照片不能为空", trigger: "blur" },
        ],
        reviewStatus: [
          { required: true, message: "评审状态不能为空", trigger: "change" },
        ],
        reviewStandard: [
          { required: true, message: "评审标准不能为空", trigger: "blur" },
        ],
        scoreStandard: [
          { required: true, message: "评分标准不能为空", trigger: "blur" },
        ],
        isDelete: [
          { required: true, message: "是否删除不能为空", trigger: "blur" },
        ],
        evaGroupId: [
          { required: true, message: "查评分组的id不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    if (1 == this.$route.query.page) {
      // 接收数据合并至搜索表单
      this.queryParams = Object.assign(
        this.queryParams,
        this.$route.query.queryParams
      );
      //日期回显
      if (undefined != this.$route.query.time) {
        this.dateRange = Object.values(this.$route.query.time);
        // this.dateRange = this.$route.query.time;
      }
      if (this.filterText != undefined) {
        this.filterText = this.$route.query.filterText;
      }
    }
    this.getList();
    this.queryTreeDataList();
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    },
  },
  methods: {
    dragControllerDiv() {
      let left = document.getElementById("left-tree");
      let line = document.getElementById("resize");
      let right = document.getElementById("right-content");
      console.log(document);
      // 鼠标按下事件
      line.onmousedown = function (e) {
        let startX = e.clientX;
        line.left = line.offsetLeft;
        // 鼠标拖动事件
        document.onmousemove = function (e) {
          let moveLen = line.left + (e.clientX - startX);
          if (
            moveLen >= document.body.clientWidth * 0.1 &&
            moveLen <= document.body.clientWidth * 0.4
          ) {
            line.style.left = moveLen + "px";
            left.style.width = moveLen + "px";
            console.log(document.body.clientWidth);
            right.style.width = document.body.clientWidth - moveLen + "px";
          }
        };
        document.onmouseup = function () {
          document.onmousemove = null;
          document.onmouseup = null;
        };
      };
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.year.indexOf(value) !== -1;
    },
    handleRowDblClick(row, column, event) {
      const valueToCopy = row[column.property];
      if (
        valueToCopy !== null &&
        valueToCopy !== undefined &&
        valueToCopy !== ""
      ) {
        this.copyToClipboard(valueToCopy);
        this.$message.success("已复制到剪贴板");
      }
    },
    copyToClipboard(text) {
      const el = document.createElement("textarea");
      el.value = text;
      el.style.position = "absolute";
      el.style.left = "-9999px";
      document.body.appendChild(el);
      el.select();
      document.execCommand("copy");
      document.body.removeChild(el);
    },
    /** 查询项目查评列表 */
    getList() {
      this.loading = true;
      listGropingRecord(
        this.addDateRange(this.queryParams, this.dateRange)
      ).then((response) => {
        this.evaluationList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getTagText(isProblem) {
      if (isProblem == "0") {
        return "否";
      } else if (isProblem == "1") {
        return "是";
      } else {
        return "";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        reviewEvents: undefined,
        evaluationElements: undefined,
        examinerCode: undefined,
        examiner: undefined,
        isApply: undefined,
        lookWorkCase: undefined,
        evaluateCase: undefined,
        isInnovate: undefined,
        evaluateObject: undefined,
        backingMaterial: undefined,
        lookPapersCase: undefined,
        deduct: undefined,
        isProblem: undefined,
        problem: undefined,
        isGreatProblem: undefined,
        rectifySuggest: undefined,
        scenePhoto: undefined,
        reviewStatus: undefined,
        reviewStandard: undefined,
        scoreStandard: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        isDelete: undefined,
        evaGroupId: undefined,
        deptCode: undefined,
        deptName: undefined,
        responsibleCode: undefined,
        responsibleName: undefined,
        requireOkTime: undefined,
        okTime: undefined,
        requireSituation: undefined,
        okPhoto: undefined,
        deductPursuant: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
      };
      this.resetForm("queryForm");
      this.dateRange = [];
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加项目查评";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getEvaluation(id).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改项目查评";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateGroping(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addGroping(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    handelTreeChange(data, node) {
      // 使用递归函数查找父级节点
      const parentNode = this.findParentNode(this.treeData, node.data);
      if (data.id !== undefined) {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
        };
        this.queryParams.reviewEventsId = data.id;
        listGropingRecord(this.queryParams).then((res) => {
          this.evaluationList = res.rows;
          this.total = res.total;
        });
      } else if (parentNode === null) {
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
        };
        let arr = [
          `${data.year.slice(0, 4)}-01-01 00:00:00`,
          `${data.year.slice(0, 4)}-12-31 23:59:59`,
        ];
        this.getlistGropingRecord(arr);
      } else {
        if (parentNode) {
          this.queryParams = {
            pageNum: 1,
            pageSize: 10,
          };
          let arr = [
            `${parentNode.year.slice(0, 4)}-${data.year.slice(
              0,
              2
            )}-01 00:00:00`,
            `${parentNode.year.slice(0, 4)}-${data.year.slice(
              0,
              2
            )}-31 23:59:59`,
          ];
          this.getlistGropingRecord(arr);
        }
      }
    },
    getlistGropingRecord(arr) {
      listGropingRecord(this.addDateRange(this.queryParams, arr)).then(
        (res) => {
          this.evaluationList = res.rows;
          this.total = res.total;
        }
      );
    },
    findParentNode(nodes, targetNode) {
      for (const node of nodes) {
        if (node.children) {
          if (node.children.some((child) => child === targetNode)) {
            return node;
          } else {
            const found = this.findParentNode(node.children, targetNode);
            if (found) return found;
          }
        }
      }
      return null;
    },
    queryTreeDataList() {
      listGropingRecordTree().then((response) => {
        const tree = [];
        // 使用对象来以 year 为键存储每个年份的节点
        const yearNodes = {};
        for (const item of response) {
          const { year, month, reviewEvents } = item;
          // 检查是否已经有该年份的节点，没有则创建一个
          if (!yearNodes[year]) {
            yearNodes[year] = {
              year,
              children: [],
            };
            tree.push(yearNodes[year]);
          }
          // 创建月份节点，并将其添加到年份节点的 children 中
          const monthNode = {
            month,
            reviewEvents,
          };
          yearNodes[year].children.push(monthNode);
        }
        const transformedData = tree.map((yearNode) => {
          return {
            year: `${yearNode.year}年`,
            children: yearNode.children.map((monthNode) => {
              return {
                year: `${monthNode.month}月`,
                children: monthNode.reviewEvents.map((event) => {
                  return {
                    id: event.id,
                    year: event.events,
                  };
                }),
              };
            }),
          };
        });
        this.treeData = transformedData;
        return tree;
      });
    },
    handleLinkClick(row) {
      console.log(this.filterText);
      this.$router.push({
        path: "/review/localEvaluation/beforEvalutionForm",
        query: {
          row: row,
          record: 1,
          queryParams: this.queryParams,
          filterText: this.filterText,
        },
      });
    },
  },
};
</script>

<style>
.el-tooltip__popper {
  max-width: 30%;
  padding-bottom: 5px !important;
  display: -webkit-box;
  overflow: hidden;
  text-overflow: ellipsis;
  -webkit-line-clamp: 15;
  -webkit-box-orient: vertical;
}
.el-tooltip__popper,
.el-tooltip__popper.is-dark {
  background: rgb(48, 65, 86) !important;
  color: #fff !important;
  line-height: 24px;
}
.contnet {
  display: flex;
}
.left-tree {
  position: relative;
  height: 100%;
  /*background: #fff;*/
  /*box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);*/
  /*border-radius: 4px;*/
  /*vertical-align: top;*/
  display: inline-block;
  box-sizing: border-box;
  -ms-flex-negative: 0;
  flex-shrink: 0;
  /*padding: 10px 0 0 10px;*/
  /*margin-right: 8px;*/
}
.resize {
  cursor: col-resize;
  position: absolute;
  top: 45%;
  right: -8px;
  background-color: #d6d6d6;
  border-radius: 5px;
  margin-top: -10px;
  width: 10px;
  height: 50px;
  background-size: cover;
  background-position: 50%;
  font-size: 32px;
  color: #fff;
}
.right-content {
  display: inline-block;
  width: calc(100% - 310px);
  /*height: 100%;*/
  /*background: #fff;*/
  /*-webkit-box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);*/
  /*box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.050980392156862744);*/
  /*border-radius: 4px;*/
  /*-webkit-box-sizing: border-box;*/
  /*box-sizing: border-box;*/
  /*padding: 10px;*/
  /*vertical-align: top;*/
  overflow: auto;
}
</style>
